package com.cauli.netdisk.module.user.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.cauli.netdisk.base.exception.MyException;
import com.cauli.netdisk.base.utils.ResultResponse;
import com.cauli.netdisk.base.utils.file.FileUploadUtils;
import com.cauli.netdisk.module.user.model.dto.UserDTO;
import com.cauli.netdisk.module.user.model.dto.UserDetailDTO;
import com.cauli.netdisk.module.user.model.dto.UserUpdateDTO;
import com.cauli.netdisk.module.user.service.UserService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author Cauli
 * @date 2023/2/24 10:26
 * @description 个人信息 前端控制器
 */
@Api(tags = "个人信息")
@ApiSort(5)
@RestController
@RequestMapping("/user/profile")
public class ProfileController {
    @Autowired
    private UserService userService;

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "获取profile")
    @GetMapping
    public ResultResponse<UserDetailDTO> getProfile() {
        long loggedInUserId = StpUtil.getLoginIdAsLong();
        UserDetailDTO userDetailDTO = userService.getUserDetail(loggedInUserId);
        return ResultResponse.ok(userDetailDTO);
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "修改profile")
    @PutMapping
    public ResultResponse<?> updateProfile(@RequestBody UserUpdateDTO userUpdateDTO) {
        userService.updateUser(userUpdateDTO);
        return ResultResponse.ok("修改成功");
    }

    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "上传用户头像")
    @PostMapping("/uploadAvatar")
    public ResultResponse<?> uploadAvatar(@RequestParam("avatarfile") MultipartFile file) {
        if (file.isEmpty()) {
            throw new MyException("用户上传头像失败");
        }
        String avatarUrl = FileUploadUtils.upload("avatar", file);
        UserDTO userDTO = new UserDTO();
        userDTO.setAvatar(avatarUrl);
        UserDetailDTO profile = userService.getProfile();
        profile.setUserDTO(userDTO);
        UserUpdateDTO userUpdateDTO = new UserUpdateDTO();
        BeanUtils.copyProperties(profile, userUpdateDTO);
        userService.updateUser(userUpdateDTO);
        return ResultResponse.ok("修改头像成功");
    }
}
